"use strict";
/**
 * @author zhaojiuyi
 * @date 2022/10/16-15:41
 * @version 1.0.0
 */

const database = require("./index")

/**
 * 根据条件查询所有数据
 * */
const selectAll = (tableName, conditionObject) => {
    return new Promise((resolve, reject) => {
        let condition = ''
        let keys = []
        let values = []
        if (conditionObject) {
            keys = Object.keys(conditionObject)
            values = Object.values(conditionObject)
            for (const key of keys) {
                condition += ` ${key}=?`
            }
            condition = condition.replace(/ /g, " and ").replace("and", "where")
        }
        const sql = `select * from ${tableName}${condition}`
        database.query(sql, values, (error, success) => {
            if (error) {
                reject(error.message)
            } else {
                resolve(success)
            }
        })

    })
}

/**
 * 插入一条数据
 * */
const insertOne = (tableName, conditionObject) => {
    return new Promise((resolve, reject) => {
        const sql = `insert into ${tableName} set ?`
        database.query(sql, conditionObject, (error, success) => {
            if (error) {
                reject(error.message)
            } else if (success.affectedRows !== 1) {
                reject(false)
            } else {
                resolve(true)
            }
        })
    })
}

/**
 * 执行指定sql
 * 返回执行结果
 * */
const getSqlResult = function (sql) {
    console.info(sql)
    return new Promise((resolve, reject) => {
        database.query(sql, function (err, result) {
            if (err) reject(false)
            resolve(result)
        })
    })
}

/**
 * 查询反馈列表数据
 * 根据时间进行排序
 * 分页
 * */
const selectFeedbackListByPage = async ({before, after, beforeDate, afterDate}) => {
    const where = beforeDate && afterDate ? `WHERE feedback_time >= "${beforeDate.replace(/T/g, ' ') + ':00'}" AND feedback_time <= "${afterDate.replace(/T/g, ' ') + ':00'}"` : ""
    const sql = 'SELECT * FROM feedback' + ` ${where} ORDER BY feedback_time DESC LIMIT ${before},${after}`
    const result = await getSqlResult(sql)
    console.log(result)
    return result
}

/**
 * 从reply表查询feedbackId的回复数据
 * */
const selectFeedbackReply = function (feedbackId) {
    const sql = ' SELECT r.reply_id,r.reply_content,r.reply_time,u.user_role,u.role_name FROM reply r' +
        ' JOIN `user` u ON u.user_id = r.user_id' +
        ` WHERE r.feedback_id = '${feedbackId}' ORDER BY r.reply_time DESC`
    return getSqlResult(sql)
}
module.exports = {
    selectAll,
    insertOne,
    selectFeedbackListByPage,
    selectFeedbackReply
}
